package com.one.square.gateway.handler;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.boot.autoconfigure.web.WebProperties.Resources;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;
import reactor.core.publisher.Mono;

/**
 * @author cwm
 * @Description 网关异常通用处理器
 * @date 2021/10/26 下午5:17
 * @Version 1.0
 */
@Slf4j
public class GlobalExceptionHandler extends DefaultErrorWebExceptionHandler {
    @Autowired
    private  GateWayExceptionHandlerAdvice gateWayExceptionHandlerAdvice;
    public GlobalExceptionHandler(ErrorAttributes errorAttributes, Resources Resources,
                                          ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, Resources, errorProperties, applicationContext);
    }
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    @Override
    protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
        Throwable throwable = getError(request);
        return ServerResponse.status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(BodyInserters.fromValue(gateWayExceptionHandlerAdvice.handle(throwable)));

    }
}
